<template>
  <div
    class="page-login"
    :style="backgroundImage"
  >
    <div class="login-box">
      <div class="top">
        <div class="logo">
          <img
            :src="checkFileUrl(configuration.bsLoginLogoImg)"
            alt
            style="max-height: 98px; max-width: 198px"
          >
          <span class="login-title">
            {{ configuration.bsTitleContent }}
          </span>
        </div>
      </div>
      <div class="mid">
        <el-form
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataRule"
          status-icon
        >
          <el-form-item prop="userName">
            <el-input
              v-model="dataForm.userName"
              v-input-rule
              class="info"
              :placeholder="$t('sys.userName') + '/' + $t('sys.mobile')"
              @keyup.enter="onSubmit(dataFormRef)"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="dataForm.password"
              v-input-rule
              class="info"
              type="password"
              :placeholder="$t('sys.password')"
              @keyup.enter="onSubmit(dataFormRef)"
            >
              >
            </el-input>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              style=""
              @click="onSubmit(dataFormRef)"
            >
              {{ $t('homes.login') }}
            </div>
            <div class="to-register">
              <div
                class="link-btn"
                @click="toFindPwd"
              >
                {{ $t('sys.retrievePassword') }}
              </div>
              <div>
                {{ $t('homes.noAccount') }}
                <span
                  class="link-btn"
                  @click="toRegister"
                >
                  {{ $t('homes.registration') }}
                </span>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <div class="bottom">
        {{ configuration.bsCopyright }}
      </div>
    </div>
    <Verify
      ref="verify"
      :captcha-type="'blockPuzzle'"
      :img-size="{ width: '400px', height: '200px' }"
      @success="login"
    />
  </div>
</template>

<script setup>
import Verify from '@/components/verifition/Verify.vue'
import cookie from 'vue-cookies'

const router = useRouter()
const userStore = useUserStore()
const allinpayStore = useAllinpayStore()

const configuration = reactive({
  bsLoginLogoImg: null,
  bsLoginBgImg: null,
  bsCopyright: null,
  bsTitleContent: null,
  bsTitleImg: null,
  bsMenuTitleOpen: null,
  bsMenuTitleClose: null
})
const setConfiguration = (val) => {
  configuration.bsLoginLogoImg = val.bsLoginLogoImg
  configuration.bsLoginBgImg = val.bsLoginBgImg
  configuration.bsCopyright = val.bsCopyright
  configuration.bsTitleContent = val.bsTitleContent
  configuration.bsTitleImg = val.bsTitleImg
  configuration.bsMenuTitleOpen = val.bsMenuTitleOpen
  configuration.bsMenuTitleClose = val.bsMenuTitleClose
}

const dataForm = reactive({
  userName: '',
  password: ''
})

const dataFormRef = ref()
const dataRule = reactive({
  userName: [{ required: true, message: $t('home.accNoNull'), trigger: 'blur' }],
  password: [{ required: true, message: $t('home.pawNoNull'), trigger: 'blur' }]
})
const verify = ref(null)
// 提交表单校验
const onSubmit = async formEl => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      verify.value.show()
    }
  })
}

onBeforeMount(() => {
  getWebConfigData()
})

let isSubmit = false
const login = (verifyResult) => {
  if (isSubmit) {
    return
  }
  isSubmit = true
  http({
    url: http.adornUrl('/shopLogin'),
    method: 'post',
    data: http.adornData({
      userName: dataForm.userName,
      passWord: encrypt(dataForm.password),
      captchaVerification: verifyResult.captchaVerification
    })
  }).then(async ({ data }) => {
    isSubmit = false
    cookie.set('bbcAuthorization_vs', data.accessToken)
    localStorage.removeItem('bbcVsNotificationMessage')
    try {
      await userStore.login()
      // 重置菜单路由
      router.options.isAddDynamicMenuRoutes = false
    } catch (error) {
      return
    }
    if (userStore.shopStatus === 4 || userStore.shopStatus === 5 || userStore.isPassShop === 0) {
      // 未开店，跳转申请开店
      await router.push({
        path: '/shop-process'
      })
    } else {
      // 已开店，跳转首页
      await router.replace({
        name: 'home'
      })
    }
    // 获取并更新通联支付配置信息（平台开启通联支付会清除所有用户token，所以重新登录时更新通联支付配置信息）
    allinpayStore.getPaySettlementType().then((paySettlementType) => {
      if (paySettlementType === 1 && data.isPassShop) {
        // 通联支付开启后，登录时判断是否创建了通联会员，如果没有创建则创建通联会员
        http({
          url: http.adornUrl('/shop/shopDetail/info'),
          method: 'get',
          params: http.adornParams()
        }).then((res) => {
          if (res.isCreateMember !== 1) {
            http({
              url: http.adornUrl('/shop/shopDetail/createAllinpayMember'),
              method: 'post'
            })
          }
        })
      }
    })
  }).catch(() => {
    isSubmit = false
  })
}

const webConfigStore = useWebConfigStore()
// 背景样式
const backgroundImage = reactive({
  width: '100%',
  height: '100%',
  backgroundSize: '100% 100%',
  position: 'fixed',
  top: 0
})

const getWebConfigData = () => {
  http({
    url: http.adornUrl('/sys/webConfig/getActivity'),
    method: 'get'
  }).then(({ data }) => {
    data = formatConfigInfo(data)
    webConfigStore.addData(data)
    setConfiguration(data)
    if (data.bsLoginBgImg) {
      backgroundImage.backgroundImage = `url(${checkFileUrl(data.bsLoginBgImg)})`
    }
  })
}

// 去注册
const toRegister = () => {
  router.push({
    path: '/register'
  })
}

// 去注册
const toFindPwd = () => {
  router.push({
    path: '/find-password'
  })
}

</script>

<style lang="scss" scoped>
.page-login {
  width: 100%;
  height: 100%;
  background: no-repeat;
  background-size: cover;
  position: fixed;
  .login-box {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    height: 100%;
    padding-top: 10%;
    .top {
      margin-bottom: 30px;
      text-align: center;
      .logo {
        font-size: 0;
        .login-title {
          font-size: 30px;
          color: #000;
          margin: 0.5em 0 0.5em 0.5em;
          vertical-align: middle;
        }
      }
    }
    .mid {
      font-size: 14px;
      .info {
        width: 100%;
        height: 40px;
      }
      .default-btn {
        height: 40px;
        line-height: 40px;
        width: 100%;
        text-align: center;
        margin-top: 32px;
      }
    }
    .bottom {
      position: absolute;
      bottom: 10%;
      width: 100%;
      color: #999;
      font-size: 12px;
      text-align: center;
    }
  }

  .to-register {
    margin-top: 10px;
    display: flex;
    width: 100%;
    justify-content: space-between;
    color: #999;
    .link-btn {
      color: #155BD4;
      &:hover{
        cursor: pointer;
      }
    }
  }
}

</style>
